package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * 文件上传和下载
 */
@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {

    @Value("${reggie.path}")
    private String basePath;

    /**
     * 文件上传
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file){
//file是一个临时文件，如果我们不转存到其他地方，请求结束后会自动清理
        log.info(file.toString());

        // 1.获取原始文件名称(有后缀)
        String originalFilename = file.getOriginalFilename();

        // 2.截取后缀----.jpg
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));

        // 3.生成新文件名---23232.jpg
        String fileName = UUID.randomUUID().toString() + suffix;

        // 4.判断文件存放目录是否存在，如果不存在则创建
        File dir = new File(basePath);//D:\\img\a\b\23232.jpg
        if(!dir.exists()){
            dir.mkdirs();
        }

        // 5.转存文件到指定目录
        File dest = new File(basePath + fileName);
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
            return R.error("上传失败");
        }

        return R.success(fileName);
    }

    /**
     * 文件下载
     * @param name
     * @param response
     */
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response){
        try {
            // 1.获取要下载的文件
            File file = new File(basePath + name);

            // 2.获得文件下载需要的输出流
            ServletOutputStream outputStream = response.getOutputStream();

            //response.setContentType("image/jpeg");
            //response.setHeader("Content-Disposition", "attachment;fileName="+name);

            // 3.获得读取文件到输入流
            FileInputStream fileInputStream = new FileInputStream(file);

            // 4.循环读取
            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = fileInputStream.read(bytes)) != -1){
                outputStream.write(bytes,0,len);
                outputStream.flush();
            }

            // 5.关闭资源
            outputStream.close();
            fileInputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
